package com.zcs.android.app.jetpack.ui.rxjava

import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.zcs.android.app.jetpack.R
import com.zcs.android.lib.base.BaseFragment
import com.zcs.android.lib.utils.LogUtils
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableOnSubscribe
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import kotlin.random.Random

class RxJavaFragment : BaseFragment() {
    companion object {
        fun newInstance() = RxJavaFragment()
    }

    private lateinit var viewModel: RxJavaViewModel

    override fun initUI() {

    }

    override fun initData() {
        // 1.创建被观察者
        val observableByFrom = Observable.create(ObservableOnSubscribe<Int> {
            it.onNext(Random.nextInt())
            it.onNext(Random.nextInt())
            it.onNext(Random.nextInt())
            it.onNext(Random.nextInt())
            // it.onError(IllegalArgumentException("Test Exception!"));
            it.onComplete()
        })

        val observer = object : Observer<Int> {
            override fun onSubscribe(d: Disposable?) {
                LogUtils.d("onSubscribe called with $d")
            }

            override fun onNext(t: Int?) {
                LogUtils.d("onNext called with val = $t")
            }

            override fun onError(e: Throwable?) {
                LogUtils.e("onError called with", e)
            }

            override fun onComplete() {
                LogUtils.d("onComplete called")
            }
        }
        observableByFrom.subscribe(observer)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.rx_java_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(RxJavaViewModel::class.java)
        // TODO: Use the ViewModel
        initUI()
        initData()
    }

}
